<?php

/*
 * Copyright (C) 2015 ziroom.com
 * 
 * I didn't order any WOO-WOO ... Maybe a YUBBA ... But no WOO-WOO!
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * This program is created by JIAO Jie.
 * The official website is <http://www.ziroom.com/>
 */

namespace Jiaojie\Autoload;

/**
 * Autoload
 * @author JIAO Jie
 * @date 2015-5-7
 * @version 1.0.0
 * @description
 */
class Register {

    /**
     * Registed Autoload Find Path
     * @var array 
     */
    public static $path = array();

    /**
     * Register Flag
     * @var boolean 
     */
    protected static $spl_register = false;

    /**
     * Instance Of Static
     * @var \Jiaojie\Autoload\ Register
     */
    protected static $instance;

    /**
     * Construct Method
     */
    protected function __construct() {
        
    }

    /**
     * Singleton Method
     * @return \Jiaojie\Autoload\Register
     */
    public static function getInstance() {
        if (!static::$instance instanceof static) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    /**
     * Deny Clone Magic Method
     * @throws \Jiaojie\Autoload\Error
     */
    protected function __clone() {
        throw new Error(Error::METHOD_NOT_ALLOW_ERROR);
    }

    /**
     * Register Absolute Path In Autoload Module
     * @param string $path Directory Absolute Path
     */
    public static function registerPath($path) {
        if (empty(static::$path)) {
            static::setRegister();
        }
        static::$path[] = $path;
    }

    /**
     * Autoload Method
     * @param string $class_name Full Class Name
     * @return boolean
     */
    public function autoload($class_name) {
        $class_file = str_replace('\\', DIRECTORY_SEPARATOR, $class_name);
        foreach (static::$path as $path) {
            if (file_exists($path . $class_file)) {
                require($path . $class_file);
                return true;
            }
        }
        return false;
    }

    /**
     * Register Autoload Method To PHP SPL Module
     * @throws \Jiaojie\Autoload\Error
     */
    private static function setRegister() {
        if (static::$spl_register) {
            throw new Error(Error::FLAG_ERROR);
        }
        ini_set('unserialize_callback_func', 'spl_autoload_call');
        if (false === spl_autoload_register(array(static::getInstance(), 'autoload'))) {
            throw new Error(Error::METHOD_RETURN_ERROR);
        }
        static::$spl_register = true;
    }

}
